function downloadme(){
    var pname = $("#personname").val();
    var namearr = pname.split(" ");
    //var initials = namearr[0].substring(0,1) + namearr[1].substring(0,1);
    //YYYYMMDD_Initials_sequencelist"
    var form = document.createElement('form');
    form.setAttribute('style', 'display:none;visibility:hidden');
    form.setAttribute('action', "/cgi-bin/gcmsjob/download_gcms_sequence.cgi");
    form.setAttribute('method', 'post');
    var vpseq_data = $('#vialsequenceid').val();
    var params = {
        'data': vpseq_data, 'fileName': new Date().yyyymmdd() + "_" + initials + "_sequencelist.csv", 'exportType':'svg'
    };
    Object.keys(params).forEach(function(key) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);
        form.appendChild(hiddenField);
    });
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

function downloadtags(){
    var pname = $("#personname").val();
    var namearr = pname.split(" ");
    var form = document.createElement('form');
    form.setAttribute('style', 'display:none;visibility:hidden');
    form.setAttribute('action', "/cgi-bin/gcmsjob/download_gcms_sequence.cgi");
    form.setAttribute('method', 'post');

    var params = {
        'data': tagseq, 'fileName': new Date().yyyymmdd() + "_" + initials + $("#expsamplelabel").val() + "_sequencetags.csv"
    };
    Object.keys(params).forEach(function(key) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);
        form.appendChild(hiddenField);
    });
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

function layRackControls(expsamplelabel){
	//initialize array to multiples of 98
	rack_vials[94] = expsamplelabel + "_Alkanes";
        rack_vials[95] = "MST";
        rack_vials[96] = "MOS";
        rack_vials[97] = "MSTFA";    
}

function refreshSequence(){
	var updatedseq = $("#vialsequenceid").val();
	vpseq = updatedseq;
	//95,MeOX60min TMS30min Splitless,jlii_Alkanes_1
	//1,OD MeOX60min TMS30min Split10,jlii_A549_ctl_1
	tagseq = "";
	rack_vials = new Array();
	var updatedseqlines = updatedseq.split("\n");
	//ignore header, alkanes, blanks
	//tags A549,ctl_1,jloo 30/1/2014
	var pdate = $("#job_date").val();
	for (var u in updatedseqlines){
		if (u == 0)
			continue;
		var uline = updatedseqlines[u].split(",")
		if (uline == null || uline.length < 3)
			continue;
		var samplename = uline[2];
		if (samplename.indexOf("_Alkanes") == -1)
			rack_vials.push(uline[2]);
		if (samplename.indexOf("_blank_") == -1 && samplename.indexOf("_pool_") == -1 && samplename.indexOf("_Alkanes") == -1){
			var sp = samplename.split("_");
			tagseq = tagseq + sp[1] + "," + sp[2] + "_" + sp[3] + "," + sp[0] + " " + pdate + " &#13;&#10;"; 
		}
	}
}

//replicates*samples, add blanks, consider additional blanks and pools
function generatevialpos(){
	tagseq = "";
	var replicates = parseInt($("#replicatecount").val());
	var conditions = $("#conditions").val();
	var sampletypessel = $("#sample_type").val();
        if (sampletypessel != null && sampletypessel !=  ""){
              sampletypessel = sampletypessel.join();//sample_types;
                sample_types = sampletypessel;
          }else{
            sample_types = "";
        }
        var celllines = sample_types.split(",");//$("#sample_type").val();

	var pname = $("#personname").val();
	if (pname == "" || conditions == "" || pname.indexOf(" ") == -1 ){
		new Messi("Name can not be empty, and it must be First Last, for initials. Cellline, conditions and replicate count must be filled in, check with Christian for exceptions", {title:"Error"});
		return;
	}
	rack_vials = new Array();	
	var expsamplelabel = "";
	if ($("#expsamplelabel").val() != ""){
		expsamplelabel = $("#expsamplelabel").val();
	}
	var conditionlist = conditions.split(",");
	var namearr = pname.split(" ");
	var pdate = $("#job_date").val();
	if (initials == null || initials == ""){
	    initials = namearr[0].substring(0,1) + namearr[1].substring(0,1);
	}
	expsamplelabel = initials + expsamplelabel;
	$("#joblabel").val(expsamplelabel);
	var alkanemethod = gcmethods[$("#method_alkane").val()];
	vpseq = "vial,method,name&#13;&#10;95," + alkanemethod + "," + expsamplelabel + "_Alkanes&#13;&#10;";	
	//layRackControls(expsamplelabel);
	/*rack_vials[93] = expsamplelabel + "_Alkanes_1";
	rack_vials[95] = "control";
	rack_vials[96] = "DerivReagent";
	rack_vials[97] = "DerivReagent";*/
	var trays = {};
	var warning = "";
	var poolbin = $("#poolbin").val();
	var blankbin = $("#blankbin").val();
	var vialpos = 0;
	var additionalControls = 0;
	//keep in mind that a tray can add up to maximum 98 vials, we want full sets? minus 4 controls?
	for (var i = 0; i< replicates; i++){
		for (var cl = 0; cl < celllines.length; cl++){
		    var cellline = celllines[cl];
		    var cellunder = "_";
                    if (cellline == "")
                        cellunder = ""; 
		    var cellsetct = cl * (conditionlist.length + 1); 
  		    for (var c = 0; c <= conditionlist.length;  c++){
			    samplename = "";
			    condition = conditionlist[c];
			    if (condition != null)
				condition = condition.trim();
			    var conditionmethod = gcmethods[$("#method_" + condition).val()];	
			    if (c < conditionlist.length){				
				samplename =  expsamplelabel + "_" + cellline + cellunder + condition.trim() + "_" + (i+1);
				tagseq = tagseq + cellline + "," + condition.trim() + "_" + (i+1) + "," + expsamplelabel + " " + pdate + " &#13;&#10;";
			    }else{
			        var blankcell = "_" + cellline;
				if (celllines.length < 1){
				    blankcell = "";
				}
				conditionmethod = gcmethods[$("#method_blank").val()];	  
				samplename = expsamplelabel + blankcell + "_blank_" + (i+1);
			    }
			    if (samplename.length >=40){
				new Messi("Your sample " + samplename + " is longer than 40 chars, check with Christian", {title:"Warning"});			
				warning = "<br><font color='red' size='-1'>warning:</font><br>Sample key " + samplename + " > 40 chars, exceeding limit";
			    }
			    //what is the check if sample type is 40, is that the total line()
			    //index 1
			    vialpos = i*(conditionlist.length+1)*celllines.length + cellsetct + (c+1) + additionalControls;
			    //index 0
			    rack_vials[vialpos-1] = samplename;
			    vpseq = vpseq + vialpos + "," + conditionmethod + "," + (samplename)+ "&#13;&#10;";  	    
			    var _pool=0;
			    if (poolbin > 0 && vialpos%poolbin == 0){
			    	additionalControls = additionalControls + 1;
				rack_vials[vialpos] = expsamplelabel + "_pool_" + (i+1);
                            	vpseq = vpseq + (vialpos + 1) + "," + conditionmethod + "," + (expsamplelabel + "_pool_" + (i+1))+ "&#13;&#10;";         
				_pool=1;
			    }
			    if (blankbin > 0 && vialpos%blankbin == 0){
                                additionalControls = additionalControls + 1;
                                rack_vials[vialpos+_pool] = expsamplelabel + "_xblank_" + (i+1);
                                vpseq = vpseq + (vialpos + 1 + _pool) + "," + conditionmethod + "," + (expsamplelabel + "_xblank_" + (i+1))+ "&#13;&#10;";
                            }	 	
			}
		}	
	}
	//check mediums and add to end
	//or if the medium must be at the end of each cell lline, then only add to last or first replicate set, vialpos needs to adjust ... 
	var mediumct = 0;
	if(document.getElementById('xmedium').checked){
		var medium_alkane_method = gcmethods[$("#medium_alkane").val()];
		mediumct = mediumct + 1;
		if (medium_alkane_method != ""){		
			vpseq = vpseq + "95," + medium_alkane_method + "," + expsamplelabel + "Medium_Alkane&#13;&#10;";
		}	
	vialpos = vialpos + 1;
	for (var i = 0; i< replicates; i++){
	for (var cl = 0; cl < celllines.length; cl++){
                    var cellline = celllines[cl];
                    var cellsetct = cl * (conditionlist.length + 1);
                    for (var c = 0; c <= conditionlist.length;  c++){
                            samplename = "";
                            condition = conditionlist[c];
                            if (condition != null)
                                condition = condition.trim();
                            var conditionmethod = gcmethods[$("#medium_" + cellline).val()];
                            if (c < conditionlist.length){
                                samplename =  expsamplelabel + "_" + cellline + "_medium_" + condition.trim() + "_" + (i+1);
                                tagseq = tagseq + cellline + " MEDIUM," + condition + "_" + (i+1) + "," + expsamplelabel + " " + pdate + " &#13;&#10;";
                            }else{
                                var blankcell = "_" + cellline;
                                if (celllines.length < 1){
                                    blankcell = "";
                                }
                                conditionmethod = gcmethods[$("#method_blank").val()];
                                samplename = expsamplelabel + blankcell + "_blank_" + (i+1);
                            }
                            //vialpos = i*(conditionlist.length+1)*celllines.length + cellsetct + (c+1) + additionalControls + existingVials;
                            rack_vials[vialpos-1] = samplename;
                            vpseq = vpseq + vialpos + "," + conditionmethod + "," + (samplename)+ "&#13;&#10;";
			    var _pool=0;
                            if (poolbin > 0 && vialpos%poolbin == 0){
                                additionalControls = additionalControls + 1;
                                rack_vials[vialpos] = expsamplelabel + "_pool_" + (i+1);
                                vpseq = vpseq + (vialpos + 1) + "," + conditionmethod + "," + (expsamplelabel + "_pool_" + (i+1))+ "&#13;&#10;";
				vialpos = vialpos + 1;
				_pool=1;
			    }
                            if (blankbin > 0 && vialpos%blankbin == 0){
                                additionalControls = additionalControls + 1;
                                rack_vials[vialpos+_pool] = expsamplelabel + "_xblank_" + (i+1);
                                vpseq = vpseq + (vialpos + 1 + _pool) + "," + conditionmethod + "," + (expsamplelabel + "_xblank_" + (i+1))+ "&#13;&#10;";
				vialpos = vialpos + 1;
			    }
			    vialpos = vialpos + 1;
                        }
                }
	}
	}
	var controlct = replicates*(celllines.length) + 1 + additionalControls;
	var totalCount = replicates*celllines.length*(conditionlist.length + 1) + 1 + additionalControls + mediumct;	
	if (mediumct > 0){
                //totalCount = (totalCount-1)*2;
		totalCount = vialpos + Math.ceil(vialpos/98);
        }
	$("#jobsummary").html("<font color='red' size='-1'><br>Job Summary:<br></font>" + replicates + " Replicates of Cell lines:" + sample_types + " Conditions:" + conditions + " Total controls: " + controlct + "<br>Total Samples: " + totalCount + warning);
	$("#total_samples").val(totalCount);
	$("#ssequence").val(vpseq);
        new Messi('Job submission requires signed form and sample vials layout in tray as depicted in map.' + '<br>Sequences: <textarea rows="12" cols="1000" style="width: 680px;height: 400px"  id="vialsequenceid" onchange="refreshSequence()">' + vpseq + '</textarea><br><br><span id="gvpprogress">Total samples: ' + totalCount + '<br><button type="button" onclick="downloadme()" >Save Sequence</button> <button type="button" onclick="downloadtags()" >Save Label Tags</button><button type="button" onclick="plotrackvial()" >View Tray Map</button></span>', {title: 'GCMS Sample Vial Sequence Map', width:'800px'});
	if (updatemode==0)
	    $("#submitspan").html('<button id="submitSequenceButton" onClick="javascript:submit_job()">Submit Job</button>');
}

function plotrackvial(){
	var pname = $("#personname").val();
	var expsamplelabel = "";
        if ($("#expsamplelabel").val() != ""){
                expsamplelabel = $("#expsamplelabel").val();
        }
        var namearr = pname.split(" ");
        if (initials == null || initials == ""){
            initials = namearr[0].substring(0,1) + namearr[1].substring(0,1);
        }
        expsamplelabel = initials + expsamplelabel;
	var projectname = projects[$("#projectname").val()];
	var url = "rackvials.html?"+rack_vials.join() + "?" + projectname + "?" + expsamplelabel;
	window.open(
                url,'popUpWindow','height=800,width=900,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes');
}

function newPopup(url) {
	popupWindow = window.open(
		url,'popUpWindow','height=700,width=800,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
